import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/api/api_service.dart';
import 'package:flutter_app/model/search_hot_key_bean.dart';
import 'package:flutter_app/search/search_result_list_page.dart';
import 'package:flutter_app/utils/constant.dart';
import 'package:flutter_app/utils/sp_util.dart';
import 'package:fluttertoast/fluttertoast.dart';

class SearchPage extends StatefulWidget {
  @override
  _SearchPageState createState() => new _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  final _searchTeController = TextEditingController();
  List<Widget> _hotWordWidget = List();
  List<Widget> _localSearchHistoryWidgetList = List();

  void _getSearchHotKey() {
    //获取热门搜索
    ApiService().getSearchHotKey((SearchHotKeyBean searchBean) {
      for (var hotKey in searchBean.hotKey) {
        _hotWordWidget.add(GestureDetector(
          child: Chip(
            label: Text(hotKey.name),
          ),
          onTap: () {
            Navigator.push(context,
                    MaterialPageRoute(builder: (context) => SearchResultPage(searchKeyWords:hotKey.name)))
                .then((value) => _getLocalSearchHistory());
          },
        ));
      }
      setState(() {});
    });
  }

  void _getLocalSearchHistory() {
    //获取本地搜索记录
    List<String> localSearchHistoryList =
        SpUtil().getStringList(Constant.localSearchHistoryKey);
    if (_localSearchHistoryWidgetList == null) {
      return;
    }
    setState(() {
      _localSearchHistoryWidgetList.clear();
      if (localSearchHistoryList==null||localSearchHistoryList.isEmpty) {
        return;
      }
      //遍历本地搜索记录集合
      for (var historySearchKey in localSearchHistoryList) {
        //将本地所有文本内容添加到Text控件中
        _localSearchHistoryWidgetList.add(GestureDetector(
          child: Chip(
            label: Text(historySearchKey),
          ),
          onTap: () {
            Navigator.push(context,
                MaterialPageRoute(builder: (context) => SearchResultPage(searchKeyWords:historySearchKey)));
          },
        ));
      }
    });
  }

  void _clearLocalSearchHistory() {
    SpUtil().remove(Constant.localSearchHistoryKey);
    setState(() {
      _localSearchHistoryWidgetList.clear();
    });
  }

  @override
  void initState() {
    _searchTeController.addListener(() {});
    _getSearchHotKey();
    _getLocalSearchHistory();
    super.initState();
  }

  @override
  void dispose() {
    _searchTeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Container(
              width: MediaQuery.of(context).size.width,
              height: 60,
              color: Colors.blue,
              child: Stack(
                alignment: Alignment.center, //使子widget居中对齐
                children: [
                  Positioned(
                      left: 10,
                      bottom: 15,
                      child: GestureDetector(
                        child: Icon(
                          Icons.arrow_back,
                          color: Colors.white,
                        ),
                        onTap: () {
                          Navigator.of(context).pop();
                        },
                      )),
                  Positioned(
                    bottom: 10,
                    child: Container(
                      width: MediaQuery.of(context).size.width - 100,
                      height: 40,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                          color: Colors.white.withOpacity(0.5),
                          borderRadius: BorderRadius.circular(35)),
                      child: TextField(
                        controller: _searchTeController,
                        style: TextStyle(color: Colors.white, fontSize: 15),
                        autofocus: false,
                        decoration: InputDecoration(
                            enabledBorder: InputBorder.none,
                            focusedBorder: InputBorder.none,
                            hintText: "动画",
                            hintStyle: TextStyle(color: Colors.white),
                            helperStyle:
                                TextStyle(color: Colors.grey, fontSize: 15),
                            prefixIcon: Icon(
                              Icons.search,
                              color: Colors.white,
                            ),
                            suffixIcon: IconButton(
                              iconSize: 20,
                              icon: Icon(
                                Icons.clear,
                                color: Colors.white,
                              ),
                              onPressed: () {
                                _searchTeController.clear();
                              },
                            )),
                      ),
                    ),
                  ),
                  Positioned(
                      right: 10,
                      bottom: 15,
                      child: GestureDetector(
                        child: Text(
                          "搜索",
                          style: TextStyle(color: Colors.white, fontSize: 18),
                        ),
                        onTap: () {
                          if (_searchTeController.text.isEmpty) {
                            Fluttertoast.showToast(msg: "请输入搜索内容");
                          } else {
                            Navigator.push(context, MaterialPageRoute(builder: (context)=>SearchResultPage(searchKeyWords:_searchTeController.text.trim().toString())));
                          }
                        },
                      ))
                ],
              ),
            ),
            _searchHistoryWidget(),
            _hotSearchWidget()
          ],
        ),
      ),
    );
  }

  Widget _searchHistoryWidget() {
    return Visibility(
        visible: _localSearchHistoryWidgetList.length == 0 ? false : true,
        child: Padding(
          padding: EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                children: [
                  Text(
                    "搜索历史",
                    style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.black),
                  ),
                  Expanded(child: SizedBox()),
                  IconButton(
                      alignment: Alignment.bottomRight,
                      icon: Icon(Icons.restore_from_trash),
                      onPressed: () {
                        _clearLocalSearchHistory();
                      })
                ],
              ),
              Wrap(
                //每一行（列）子Widget在纵（横）轴上的排列，全部子Widget从顶部开始展示
                alignment: WrapAlignment.start,
                //设置widget与widget在水平或者垂直轴上的间距
                runAlignment: WrapAlignment.start,
                //在direction: Axis.horizontal的时候指左右两个Widget的间距,在direction: Axis.vertical的时候指上下两个widget的间距
                spacing: 15.0,
                children: _localSearchHistoryWidgetList,
              )
            ],
          ),
        ));
  }

  Widget _hotSearchWidget() {
    return Padding(
      padding: EdgeInsets.all(20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            "热门搜索",
            style: TextStyle(
                fontSize: 20, fontWeight: FontWeight.bold, color: Colors.black),
          ),
          Wrap(
            alignment: WrapAlignment.start,
            spacing: 15,
            runSpacing: 1.0,
            children: _hotWordWidget,
          )
        ],
      ),
    );
  }
}
